from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
import json
from . import models
from .froms import UserForm, RegisterForm
import hashlib

# form方式提交上传文件页面
# def toFormUpload(request):
#     return render(request,'ajaxTest/form_upload.html')


def toAjaxIndex(request):
    return render(request, "ajaxTest/ajaxIndex.html")


# jquery get()方法:
def sumGet(request):
    a = request.GET["a"]
    b = request.GET["b"]
    cs = int(a) + int(b)
    r = HttpResponse(str(cs))
    return r


# ajax发送数据
def ajaxSend(request):
    if request.method == "POST":
        print(request.POST)
        data = {"status": "200", "msg": "请求执行成功", "data": ["101", "102", ""]}
        return HttpResponse(json.dumps(data))
    else:
        return render(request, "ajaxTest/ajaxIndex.html")


# ajax get发送数据
def sumAjax(request):
    # time.sleep(10)  #不影响页面发送其他的请求
    i1 = int(request.GET.get("i1"))
    i2 = int(request.GET.get("i2"))
    ret = i1 + i2
    return JsonResponse(ret, safe=False)


def toIndex(request):
    return render(request, "ajaxTest/index.html")


def login(request):
    # 不允许重复登录
    if request.session.get("is_login", None):
        return redirect("/ajaxTest/toIndex/")

    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():
            username = login_form.cleaned_data["username"]
            password = login_form.cleaned_data["password"]
            try:
                user = models.User.objects.get(name=username)
                if user.password == hash_code(password):  # 哈希值和数据库内的值进行比对
                    # 向session字典内写入用户状态和数据
                    request.session["is_login"] = True
                    request.session["user_id"] = user.id
                    request.session["user_name"] = user.name
                    return redirect("/ajaxTest/toIndex/")
                else:
                    message = "密码不正确！"
            except:
                message = "用户不存在！"
        return render(request, "ajaxTest/login.html", locals())

    login_form = UserForm()
    return render(request, "ajaxTest/login.html", locals())


def register(request):
    if request.session.get("is_login", None):
        # 登录状态不允许注册。你可以修改这条原则！
        return redirect("/ajaxTest/toIndex/")
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data["username"]
            password1 = register_form.cleaned_data["password1"]
            password2 = register_form.cleaned_data["password2"]
            email = register_form.cleaned_data["email"]
            sex = register_form.cleaned_data["sex"]
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
                return render(request, "ajaxTest/register.html", locals())
            else:
                same_name_user = models.User.objects.filter(name=username)
                if same_name_user:  # 用户名唯一
                    message = "用户已经存在，请重新选择用户名！"
                    return render(request, "ajaxTest/register.html", locals())
                same_email_user = models.User.objects.filter(email=email)
                if same_email_user:  # 邮箱地址唯一
                    message = "该邮箱地址已被注册，请使用别的邮箱！"
                    return render(request, "ajaxTest/register.html", locals())

                # 当一切都OK的情况下，创建新用户

                new_user = models.User.objects.create()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                return redirect("/ajaxTest/login/")  # 自动跳转到登录页面
    register_form = RegisterForm()
    return render(request, "ajaxTest/register.html", locals())


def logout(request):
    if not request.session.get("is_login", None):
        # 如果本来就未登录，也就没有登出一说
        return redirect("/ajaxTest/toIndex/")
    request.session.flush()
    # 或者使用下面的方法
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect("/ajaxTest/toIndex/")


def hash_code(s, salt="mysite_login"):  # 加点盐
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()


def toJsonTest(request):
    return render(request, "ajaxTest/jsonTest.html")

# json格式数据发送与接收
def jsonSendReceive(request):
    print(request.POST)
    print(request.method)
    print(type(request.POST))
    data = {
        "patient_name": "张三",
        "age": "25",
        "patient_id": "19000347",
        "诊断": "上呼吸道感染",
    }
    listdata = ["张三", "25", "19000347", "上呼吸道感染"]
    # HttpResponse需要我们自己前后台进行序列化与反序列化
    # 而JasonResponse则把序列化和反序列化封装了起来，我们直接传入可序列化的字符串，在前台就能收到对应的数据

    # return HttpResponse(json.dumps(listdata),content_type='application/json')
    # return HttpResponse(json.dumps(data),content_type='application/json')# content_type='application/json' 解决中文乱码
    # return JsonResponse(listdata,safe=False)
    return JsonResponse(data)
